package seeqpod;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import javax.swing.JOptionPane;

public class InOut {

    SeeqPod sp = new SeeqPod();

    public int getsize(URL url) {
        int size = 0;
        try {
            
            URLConnection conn = url.openConnection();
            size = conn.getContentLength();
            conn.setReadTimeout(100);
            conn.getInputStream().close();
            
        } catch (Exception e) {
            
            e.printStackTrace();
        }
        return size;
    }
    public int getsize(String address){
        return getsize(getURL(address));
    }

    public boolean urlisvalid(URL url) {
        try {
            System.out.println("URL Check: " + url.toString());
            HttpURLConnection connection = (HttpURLConnection)url.openConnection();
            connection.setReadTimeout(500);
            if(connection.getResponseCode() > 299)
                return true;
        } catch (Exception e){
            return false;
        }
        return true;
    }
    public boolean urlisvalid(String address){
        return urlisvalid(getURL(address));
    }

    public void download(URL url, File F) {
        OutputStream out = null;
        InputStream in = null;
        try {

            out = new BufferedOutputStream(new FileOutputStream(F));

            in = url.openConnection().getInputStream();
            byte[] buffer = new byte[1024];
            int numRead;
            long numWritten = 0;
            while ((numRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, numRead);
                numWritten += numRead;
            }
            System.out.println(F.getPath() + "\t" + numWritten);
        } catch (Exception exception) {
            exception.printStackTrace();
            F.delete();
            JOptionPane.showMessageDialog(null, F.getName() + ": URL not valid, try another one", "Oh no!", JOptionPane.INFORMATION_MESSAGE);

        } finally {
            try {
                if (in != null) {
                    in.close();
                }
                if (out != null) {
                    out.close();
                }
            } catch (IOException ioe) {
            }
        }
    }
    public void download(String address, File F) {
        download(getURL(address), F);
    }

    public String readData(URL url) {
        try {
            return new BufferedReader(new InputStreamReader(url.openStream())).readLine();

        } catch (IOException ex) {}

        return "";
    }
    public String readData(String address){
        return readData(getURL(address));
    }
    
    public URL getURL(String address) {
        try {
            return new URL(address.replaceAll(" ", "%20").replaceAll("~", "%7E"));
        } catch (MalformedURLException ex) { }
        return null;
    }

    public SeeqPodRecommendation[] DiscoverSeeqResults(String artist, String song) {

        download("http://www.seeqpod.com/api/v0.2/" + SeeqPod.KEY + "/music/recommendations/artists/" + artist + "/" + song, new File("discover.xml"));

        File f = new File("discover.xml");


        String str = null;
        try {
            BufferedReader in = new BufferedReader(new FileReader(f));
            str = in.readLine();
        } catch (IOException e) {
            e.printStackTrace();
        }
        int total = 0, index = 0;
        while (str.indexOf("<track>", index) > -1) {
            total++;
            index = str.indexOf("<track>", index) + 7;
        }

        SeeqPodRecommendation recommend[] = new SeeqPodRecommendation[total];
        int trackindex = str.indexOf("</title>") + 8;

        for (int i = 0; i < total; i++) {
            recommend[i] = new SeeqPodRecommendation();
            recommend[i].setLocation(str.substring(str.indexOf("<location>", trackindex) + 10, str.indexOf("</location>", trackindex)));
            recommend[i].setTitle(str.substring(str.indexOf("<title>", trackindex) + 7, str.indexOf("</title>", trackindex)));
            recommend[i].setCreator(str.substring(str.indexOf("<creator>", trackindex) + 9, str.indexOf("</creator>", trackindex)));
            if (str.indexOf("<album>", trackindex) != -1 && str.indexOf("<album>", trackindex) < str.indexOf("</track>", trackindex)) {
                recommend[i].setAlbum(str.substring(str.indexOf("<album>", trackindex) + 7, str.indexOf("</album>", trackindex)));
            }

            if (str.indexOf("<genre>", trackindex) != -1 && str.indexOf("<genre>", trackindex) < str.indexOf("</genre>", trackindex)) {
                recommend[i].setGenre(str.substring(str.indexOf("<genre>", trackindex) + 7, str.indexOf("</genre>", trackindex)));
            }
            recommend[i].setSeeqPodTrack();
            trackindex = str.indexOf("</track>", trackindex) + 8;
        }
        return recommend;
    }

    public SeeqPodSpellCheck[] SeeqPodSpell(String query, String KEY) {
        download("http://www.seeqpod.com/api/v0.2/" + KEY + "/music/spellcheck/" + query, new File("spell.xml"));

        File f = new File("spell.xml");

        StringBuilder str1 = new StringBuilder(5000);

        try {
            BufferedReader in = new BufferedReader(new FileReader(f));
            String line = in.readLine();
            for (int count = 0; line != null; count++) {
                str1.append(line);
                line = in.readLine();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        String str = str1.toString();
        int total = 0, index = 0;
        while (str.indexOf("<result>", index) > -1) {
            total++;
            index = str.indexOf("<result>", index) + 8;
        }

        SeeqPodSpellCheck recommend[] = new SeeqPodSpellCheck[total];
        int trackindex = str.indexOf("<resultList>") + 12;
        for (int i = 0; i < total; i++) {
            recommend[i] = new SeeqPodSpellCheck();
            recommend[i].setArtist(str.substring(str.indexOf("<artist>", trackindex) + 8, str.indexOf("</artist>", trackindex)));
            recommend[i].setScore((Float.parseFloat(str.substring(str.indexOf("<score>", trackindex) + 7, str.indexOf("</score>", trackindex)))));

            trackindex = str.indexOf("</result>", trackindex) + 8;
        }
        return recommend;
    }
}

